import 'dart:io';
import 'dart:typed_data';
import 'dart:ui';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:panda/base/Constant.dart';
import 'package:panda/entity/order_list_entity.dart';
import 'package:panda/http/Api.dart';
import 'package:panda/util/LoadingUtil.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

class OrderHuiZhiPage extends StatefulWidget {
  OrderListDataData order;
  OrderHuiZhiPage({Key key, this.order}) : super(key: key);

  @override
  _OrderHuiZhiPageState createState() => _OrderHuiZhiPageState();
}

class _OrderHuiZhiPageState extends State<OrderHuiZhiPage> {
  GlobalKey key = new GlobalKey();
  double total = 0.00,nums=0;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    for (int i = 0; i < widget.order.datas.length; i++) {
      total += double.parse(widget.order.datas[i].price) *
          double.parse(widget.order.datas[i].num);
          nums+=double.parse(widget.order.datas[i].num);
    }
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          title: Text('订单回执',
              style: TextStyle(
                  fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE),
                  color: Colors.black)),
          backgroundColor: Colors.white,
          brightness: Brightness.light,
          centerTitle: true,
          iconTheme: new IconThemeData(color: Colors.black),
          elevation: 0.5,
        ),
        body: SingleChildScrollView(
          child: Container(
            height: MediaQuery.of(context).size.height - kToolbarHeight - 56,
            color: f0Color,
            child: Column(
              children: [
                RepaintBoundary(
                    key: key,
                    child: Container(
                        color: f0Color,
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Container(
                              color: mainColor,
                              padding: EdgeInsets.fromLTRB(10,0,10,0),
                              child: Row(
                                children: [
                                  Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Text('下单回执',
                                          style: TextStyle(
                                              fontSize: ScreenUtil.getInstance()
                                                  .setSp(BIG_FONT_SIZE),
                                              color: Colors.white)),
                                      Container(height: 10),
                                      Text('订单号: ' + widget.order.order_num,
                                          style: TextStyle(
                                              fontSize: ScreenUtil.getInstance()
                                                  .setSp(BIG_FONT_SIZE - 5),
                                              color: Colors.white)),
                                      Container(height: 5),
                                      Text('下单时间: ' + widget.order.create_time,
                                          style: TextStyle(
                                              fontSize: ScreenUtil.getInstance()
                                                  .setSp(BIG_FONT_SIZE - 5),
                                              color: Colors.white))
                                    ],
                                  ),
                                  Expanded(child: Center()),
                                  Image.asset(
                                    "images/menpai.png",
                                    fit: BoxFit.fitHeight,
                                    height: 130,
                                  )
                                ],
                              ),
                            ),
                            Stack(
                              children: [
                                Column(
                                  children: [
                                    Stack(
                                      children: [
                                        Container(
                                          color: mainColor,
                                          height: 20,
                                        ),
                                        Container(
                                          margin: EdgeInsets.fromLTRB(
                                              10, 0, 10, 10),
                                          decoration: BoxDecoration(
                                              color: white,
                                              borderRadius:
                                                  BorderRadius.circular(10)),
                                          child: Column(
                                            crossAxisAlignment:
                                                CrossAxisAlignment.start,
                                            children: [
                                              Container(
                                                padding: EdgeInsets.all(10),
                                                child: Text('收件人信息',
                                                    style: TextStyle(
                                                        fontSize: 14)),
                                              ),
                                              Padding(
                                                padding: EdgeInsets.fromLTRB(
                                                    15, 0, 15, 10),
                                                child: new Row(
                                                  crossAxisAlignment:
                                                      CrossAxisAlignment.start,
                                                  children: <Widget>[
                                                    Expanded(
                                                      child: Padding(
                                                        padding:
                                                            EdgeInsets.fromLTRB(
                                                                10, 0, 10, 0),
                                                        child: new Column(
                                                          crossAxisAlignment:
                                                              CrossAxisAlignment
                                                                  .start,
                                                          children: <Widget>[
                                                            Text(
                                                                "*" +
                                                                    (widget.order.consignee.substring(
                                                                        1,
                                                                        widget
                                                                            .order
                                                                            .consignee
                                                                            .length)) +
                                                                    "   " +
                                                                    (widget
                                                                        .order
                                                                        .contact_number
                                                                        .substring(
                                                                            0,
                                                                            3)) +
                                                                    "****" +
                                                                    (widget
                                                                        .order
                                                                        .contact_number
                                                                        .substring(
                                                                            7,
                                                                            11)),
                                                                style: TextStyle(
                                                                    color:
                                                                        black,
                                                                    fontSize: ScreenUtil
                                                                            .getInstance()
                                                                        .setSp(
                                                                            BIG_FONT_SIZE),
                                                                    fontWeight:
                                                                        FontWeight
                                                                            .w500)),
                                                            Padding(
                                                              padding:
                                                                  EdgeInsets
                                                                      .fromLTRB(
                                                                          0,
                                                                          4,
                                                                          0,
                                                                          0),
                                                              child: Text(
                                                                  widget.order
                                                                          .address
                                                                          .substring(
                                                                              0,
                                                                              widget.order.address.length -
                                                                                  9) +
                                                                      "****",
                                                                  style:
                                                                      TextStyle(
                                                                    color:
                                                                        black_99,
                                                                    fontSize: ScreenUtil
                                                                            .getInstance()
                                                                        .setSp(SMALL_FONT_SIZE +
                                                                            3),
                                                                  )),
                                                            )
                                                          ],
                                                        ),
                                                      ),
                                                    )
                                                  ],
                                                ),
                                              ),
                                            ],
                                          ),
                                        )
                                      ],
                                    ),
                                    Container(
                                      color: white,
                                      padding:
                                          EdgeInsets.fromLTRB(15, 0, 15, 10),
                                      child: ListView.builder(
                                          shrinkWrap: true,
                                          itemBuilder: (BuildContext context,
                                              int index) {
                                            return Container(
                                              padding: EdgeInsets.fromLTRB(
                                                  0, 20, 0, 0),
                                              child: new Row(
                                                crossAxisAlignment:
                                                    CrossAxisAlignment.start,
                                                children: <Widget>[
                                                  widget.order == null ||
                                                          widget
                                                                  .order
                                                                  .datas[index]
                                                                  .img ==
                                                              ""
                                                      ? Image.asset(
                                                          'images/app_icon.png',
                                                          width: ScreenUtil
                                                                  .getInstance()
                                                              .setWidth(160),
                                                          height: ScreenUtil
                                                                  .getInstance()
                                                              .setWidth(160),
                                                          fit: BoxFit.fill,
                                                        )
                                                      : CachedNetworkImage(
                                                          imageUrl: Api
                                                                  .ImgBaseUrl +
                                                              widget
                                                                  .order
                                                                  .datas[index]
                                                                  .img,
                                                          width: ScreenUtil
                                                                  .getInstance()
                                                              .setWidth(160),
                                                          height: ScreenUtil
                                                                  .getInstance()
                                                              .setWidth(160),
                                                          fit: BoxFit.fill,
                                                        ),
                                                  Expanded(
                                                    flex: 1,
                                                    child: Container(
                                                      padding:
                                                          EdgeInsets.fromLTRB(
                                                              10, 0, 5, 0),
                                                      child: Column(
                                                        crossAxisAlignment:
                                                            CrossAxisAlignment
                                                                .start,
                                                        children: <Widget>[
                                                          Text(
                                                            widget.order == null
                                                                ? ""
                                                                : widget
                                                                    .order
                                                                    .datas[
                                                                        index]
                                                                    .goods_name,
                                                            maxLines: 2,
                                                            overflow:
                                                                TextOverflow
                                                                    .ellipsis,
                                                            style: TextStyle(
                                                                fontSize: ScreenUtil
                                                                        .getInstance()
                                                                    .setSp(
                                                                        NORMAL_FONT_SIZE +
                                                                            2),
                                                                color: black),
                                                          ),
                                                          Padding(
                                                            padding: EdgeInsets
                                                                .fromLTRB(
                                                                    0, 5, 5, 5),
                                                            child: Html(
                                                              defaultTextStyle: TextStyle(
                                                                  fontSize: ScreenUtil
                                                                          .getInstance()
                                                                      .setSp(
                                                                          NORMAL_FONT_SIZE),
                                                                  color: black),
                                                              data: widget.order ==
                                                                      null
                                                                  ? ""
                                                                  : widget
                                                                      .order
                                                                      .datas[
                                                                          index]
                                                                      .sku_str,
                                                            ),
                                                          ),
                                                          Text(
                                                            widget.order == null
                                                                ? ""
                                                                : '¥' +
                                                                    widget
                                                                        .order
                                                                        .datas[
                                                                            index]
                                                                        .price
                                                                        .toString(),
                                                            style: TextStyle(
                                                                fontSize: ScreenUtil
                                                                        .getInstance()
                                                                    .setSp(
                                                                        BIG_FONT_SIZE),
                                                                color:
                                                                    mainColor),
                                                          ),
                                                        ],
                                                      ),
                                                    ),
                                                  ),
                                                ],
                                              ),
                                            );
                                          },
                                          itemCount: widget.order == null
                                              ? 0
                                              : widget.order.datas.length),
                                    ),
                                  ],
                                ),
                                Positioned(
                                    top: 40,
                                    right: 10,
                                    child: Image.asset(
                                      "images/xdcg.png",
                                      width: ScreenUtil.getInstance()
                                          .setHeight(240),
                                    ))
                              ],
                            ),
                            Container(
                              margin: EdgeInsets.only(top: 10),
                              padding: EdgeInsets.all(10),
                              color: white,
                              child: Row(
                                children: [
                                  Text('商品数量: ',
                                      style: TextStyle(
                                          fontSize: ScreenUtil.getInstance()
                                              .setSp(BIG_FONT_SIZE - 5),
                                          color: Colors.black)),
                                  Expanded(child: Center()),
                                  Text("$nums",
                                      style: TextStyle(
                                          fontSize: ScreenUtil.getInstance()
                                              .setSp(BIG_FONT_SIZE - 5),
                                          color: Colors.black))
                                ],
                              ),
                            ),
                            Container(
                              margin: EdgeInsets.only(top: 1),
                              padding: EdgeInsets.all(10),
                              color: white,
                              child: Row(
                                children: [
                                  Text('订单总额: ',
                                      style: TextStyle(
                                          fontSize: ScreenUtil.getInstance()
                                              .setSp(BIG_FONT_SIZE - 5),
                                          color: Colors.black)),
                                  Expanded(child: Center()),
                                  Text(MONEY + "$total",
                                      style: TextStyle(
                                          fontSize: ScreenUtil.getInstance()
                                              .setSp(BIG_FONT_SIZE - 5),
                                          color: Colors.black))
                                ],
                              ),
                            ),
                            Container(
                              margin: EdgeInsets.only(top: 1),
                              padding: EdgeInsets.all(10),
                              color: white,
                              child: Row(
                                children: [
                                  Text('运费: ',
                                      style: TextStyle(
                                          fontSize: ScreenUtil.getInstance()
                                              .setSp(BIG_FONT_SIZE - 5),
                                          color: Colors.black)),
                                  Expanded(child: Center()),
                                  Text(widget.order.postage,
                                      style: TextStyle(
                                          fontSize: ScreenUtil.getInstance()
                                              .setSp(BIG_FONT_SIZE - 5),
                                          color: Colors.black))
                                ],
                              ),
                            ),
                            Padding(
                              padding: EdgeInsets.fromLTRB(0, 25, 15, 15),
                              child: Row(
                                children: <Widget>[
                                  Expanded(
                                    child: Text('',
                                        style: TextStyle(
                                            color: black, fontSize: 14)),
                                  ),
                                  Text('合计: ',
                                      style: TextStyle(
                                          color: black_99, fontSize: 13)),
                                  Text(
                                    widget.order == null
                                        ? ""
                                        : '¥' +
                                            formatNum(total +
                                                    double.parse(widget.order
                                                                .postage ==
                                                            "null"
                                                        ? '0'
                                                        : widget.order.postage),2)
                                                ,
                                    style: TextStyle(
                                        fontSize:
                                            ScreenUtil.getInstance().setSp(35),
                                        color: mainColor),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ))),
                Expanded(child: Center()),
                // Expanded(
                //   child: Center(),
                // ),
                GestureDetector(
                  onTap: () {
                    showDialog(
                        context: context,
                        barrierDismissible: false,
                        builder: (_) {
                          return new NetLoadingDialog(
                            loadingText: "保存中...",
                            bgColor: Color.fromARGB(255, 0, 0, 0),
                            requestCallBack: null,
                            outsideDismiss: false,
                          );
                        });
                    _capturePng();
                  },
                  behavior: HitTestBehavior.opaque,
                  child: Container(
                    alignment: Alignment.center,
                    padding: EdgeInsets.all(10),
                    margin: EdgeInsets.all(10),
                    color: mainColor,
                    width: double.infinity,
                    child: Text(
                      '保存回执',
                      style: TextStyle(
                          color: white,
                          fontSize: ScreenUtil.getInstance().setSp(35)),
                    ),
                  ),
                )
              ],
            ),
          ),
        ));
  }
String formatNum(double num, int postion) {
    if ((num.toString().length - num.toString().lastIndexOf(".") - 1) <
        postion) {
      return num.toStringAsFixed(postion)
          .substring(0, num.toString().lastIndexOf(".") + postion + 1)
          .toString();
    } else {
      return num.toString()
          .substring(0, num.toString().lastIndexOf(".") + postion + 1)
          .toString();
    }
  }
  _capturePng() async {
    try {
      RenderRepaintBoundary boundary = key.currentContext.findRenderObject();
      var image = await boundary.toImage(pixelRatio: 3.0);
      ByteData byteData = await image.toByteData(format: ImageByteFormat.png);
      Uint8List pngBytes = byteData.buffer.asUint8List();
      _capturePath(
          pngBytes, Platform.isIOS ? pngBytes : pngBytes.buffer.asInt8List());
      Navigator.of(context).pop(1);
      return pngBytes;
    } catch (e) {
      Navigator.of(context).pop(1);
      print(e);
    }
    return null;
  }

  _capturePath(pngBytes, byteData) async {
    String fileName = DateTime.now().millisecondsSinceEpoch.toString() + ".png";
    if (Platform.isAndroid) {
      var status = await Permission.storage.status;

      if (status.isGranted) {
        Directory documentsDirectory = await getExternalStorageDirectory();
        String path = documentsDirectory.path + "/xiongmao";
        bool has = await Directory(path).exists();
        if (!has) {
          await Directory(path).create();
        }
        File file = await File(path + "/$fileName").writeAsBytes(pngBytes);
        String result = await ImageGallerySaver.saveFile(path + "/$fileName");
        if (result != null) {
          Fluttertoast.showToast(msg: "保存成功");
        } else {
          Fluttertoast.showToast(msg: "保存失败");
        }
      } else {
        await Permission.storage.request();
      }
    } else {
      Directory documentsDirectory = await getApplicationDocumentsDirectory();
      String path = documentsDirectory.path;
      File(path + "/$fileName").writeAsBytes(pngBytes);
      final result = await ImageGallerySaver.saveFile(path + "/$fileName");
      if (result) {
        // File file = File(path + "/$fileName");
        // print(file.existsSync());
        Fluttertoast.showToast(msg: "保存成功");
      } else {
        Fluttertoast.showToast(msg: "保存失败");
      }
      // } else {
      //   Fluttertoast.showToast(msg: "失败");
      // }
    }
  }
}
